package com.example.demo4;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.List;

public class FruitAdapter extends ArrayAdapter<Fruit> {
    private int resourceId;

    public FruitAdapter(@NonNull Context context, int resource, @NonNull List<Fruit> objects) {
        super(context, resource, objects);
        this.resourceId = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        //获取当前实例
        Fruit fruit=getItem(position);
        //绑定布局
        View view;
        ViewHolder viewHolder=new ViewHolder();
        //优化缓存
        if (convertView==null){
            view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
            viewHolder.fruit_img=view.findViewById(R.id.fruit_img);
            viewHolder.fruit_name=view.findViewById(R.id.fruit_name);
            view.setTag(viewHolder);//将控件实例保存到view中
        }else {
            view=convertView;
            viewHolder= (ViewHolder) view.getTag();
        }
        viewHolder.fruit_img.setImageResource(fruit.getImageId());
        viewHolder.fruit_name.setText(fruit.getName());
        return  view;
    }

    private class ViewHolder {
        ImageView fruit_img;
        TextView fruit_name;
    }
}
